<template>
  <div class="app-container">
    <el-card class="box-card" style="min-height: 80vh">
      <div slot="header" class="clearfix">
        <!-- 头部左侧 -->
        <div class="media-display">
          <el-link :underline="false" style="font-size: 20px">用户列表</el-link>
          <el-divider direction="vertical"></el-divider>
        </div>

        <!-- 头部右侧 -->
        <div style="margin-left: auto">
          <el-form :inline="true" :model="condition" class="demo-form-inline">
            <el-form-item label="用户ID">
              <el-input v-model="condition.userId" placeholder="用户ID"></el-input>
            </el-form-item>
            <el-form-item label="账号">
              <el-input v-model="condition.username" placeholder="账号"></el-input>
            </el-form-item>
            <el-form-item label="账号状态">
              <el-select v-model="condition.state" placeholder="请选择状态">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="success" plain @click="init">查询</el-button>
              <el-button style="margin-left: 10px" type="primary" plain @click="viewAll">全部用户</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 内容 -->
      <div class="text">
        <el-table
          v-loading="listLoading"
          highlight-current-row
          :data="page.list"
          fit
          style="width: 100%">
          <!--展开行-->
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="用户 ID">
                  <span>{{ props.row.userId }}</span>
                </el-form-item>
                <el-form-item label="用户账号">
                  <span>{{ props.row.username }}</span>
                </el-form-item>
                <el-form-item label="电话">
                  <span v-if="props.row.phone===undefined">暂无</span>
                  <span v-else>{{ props.row.phone }}</span>
                </el-form-item>
                <el-form-item label="密码">
                  <span>{{ props.row.password }}</span>
                  <el-popconfirm
                    confirm-but ton-text='好的'
                    cancel-button-text='不用了'
                    icon="el-icon-info"
                    icon-color="red"
                    title="是否重置密码？" @onConfirm="resetPassword(props.$index,props.row.userId)">
                    <el-button slot="reference" type="primary" size="mini" plain style="margin-left: 5px">重置密码</el-button>
                  </el-popconfirm>
                </el-form-item>
                <el-form-item label="邮箱">
                  <span v-if="props.row.email===undefined">暂无</span>
                  <span v-else>{{ props.row.email }}</span>
                </el-form-item>
                <el-form-item label="性别">
                  <span>{{ props.row.gender | genderFilter}}</span>
                </el-form-item>
                <el-form-item label="用户生日">
                  <span>{{ props.row.birthday}}</span>
                </el-form-item>
                <el-form-item label="创建时间">
                  <span>{{ props.row.createTime | timestampToTime}}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column
            type="index"
            :index="(this.page.currentPage-1)*this.page.pageSize + 1"
            width="50">
          </el-table-column>
          <el-table-column
            width="200"
            label="用户 ID"
            prop="userId">
          </el-table-column>
          <el-table-column
            width="200"
            label="用户账号"
            prop="username">
          </el-table-column>
          <el-table-column
            width="200"
            label="昵称"
            prop="nickname">
          </el-table-column>
          <el-table-column
            width="120"
            label="性别"
            prop="gender">
            <template slot-scope="scope" >
              {{ scope.row.gender | genderFilter}}
            </template>
          </el-table-column>
          <el-table-column
            width="200"
            align="center"
            label="状态(锁定/正常)">
            <template slot-scope="scope" >
              <el-popconfirm
                confirm-but ton-text='好的'
                cancel-button-text='不用了'
                icon="el-icon-info"
                icon-color="red"
                title="是否更改用户状态？"
                @cancel="console.log(123)"
                @onConfirm="modifyState(scope.$index,scope.row.userId,scope.row.state)">
                <el-switch
                  slot="reference"
                  disabled
                  v-model="scope.row.state"
                  :active-value="1"
                  :inactive-value="0">
                </el-switch>
              </el-popconfirm>
            </template>
          </el-table-column>

          <el-table-column
            width="150"
            label="购物车操作">
            <template slot-scope="scope">
              <el-button size="small" type="success" plain @click="toCart(scope.row.userId)">查看购物车</el-button>
            </template>
          </el-table-column>

          <el-table-column
            width="150"
            label="订单操作">
            <template slot-scope="scope">
              <el-button size="small" type="primary" plain @click="toUserOrder(scope.row.userId)">查看订单</el-button>
            </template>
          </el-table-column>

          <el-table-column
            width="150"
            label="账号操作">
            <template slot-scope="scope">
              <el-button size="small" type="primary" @click="getInfo(scope.$index,scope.row.userId)">修改</el-button>
              <el-button slot="reference" size="small" type="danger" :disabled="scope.row.role_name === 'super'" @click="open()">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--分页-->
        <el-pagination style="text-align: center"
                       @current-change="handleCurrentChange"
                       :current-page="this.page.currentPage"
                       :page-size="this.page.pageSize"
                       layout="total, prev, pager, next, jumper"
                       :total="this.page.total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      width="30%"
      title="修改信息"
      :visible.sync="modifyAllInfoDialog"
      :before-close="handleClose">
      <div v-loading="dialogLoading">
        <el-form :model="modifyAllInfoForm" :rules="rules" ref="modifyAllInfoForm" style="width: 80%" label-width="100px">
          <el-form-item label="用户id" prop="userId">
            <el-input v-model="modifyAllInfoForm.userId" disabled prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="username">
            <el-input v-model="modifyAllInfoForm.username" disabled prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="modifyAllInfoForm.password" prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-switch
              v-model="modifyAllInfoForm.state"
              :active-value="1"
              :inactive-value="0"
              active-text="正常"
              inactive-text="封禁">
            </el-switch>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="modifyAllInfoForm.nickname" prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="modifyAllInfoForm.email" prefix-icon="el-icon-platform-eleme"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="modifyAllInfoForm.phone" prefix-icon="el-icon-phone-outline"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyAllInfoDialog = false">取 消</el-button>
        <el-popconfirm
          style="margin-left: 10px"
          confirm-but ton-text='好的'
          cancel-button-text='不用了'
          icon="el-icon-info"
          icon-color="red"
          title="是否修改用户信息？" @onConfirm="submitForm('modifyAllInfoForm')">
          <el-button type="primary" slot="reference">确 定</el-button>
        </el-popconfirm>
      </div>
    </el-dialog>


  </div>
</template>


<script>
  import { modifyStateReq, modifyUserInfoReq, getUserByIdReq, getUserListReq, resetPasswordReq } from '@/api/userManage'

  export default {
    name: "UserList",
    data(){
      return{
        options: [{
          value: '0',
          label: '封禁'
        }, {
          value: '1',
          label: '正常'
        }],
        listLoading: true,// 表格loading
        dialogLoading: true,
        modifyAllInfoDialog: false,
        modifyAllInfoForm:{
          userId: "",
          username: "",
          password: "",
          state: true,
          nickname: "",
          email: "",
          phone: "",
          role_id: 1,
        },
        rules: {//修改密码验证规则
          password: [
            { required: true, message: '请输入原密码', trigger: 'blur' },
            { min: 3, message: '长度不小于 3 个字符 ', trigger: 'blur' }
          ],
          state: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ],
          nickname: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ],
          email: [
            { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          ],
          phone: [
            { required: true, message: '请输入电话号码', trigger: 'blur' },
          ],
        },
        globalIndex : 0,

        page : {},

        condition: {
          userId: '',// 用户id
          username : '',// 账号
          state : '',// 账号状态
          currentPage: 1,
        },

      }
    },
    methods : {
      resetPassword(index, userId){
        resetPasswordReq({userId: userId}).then((response) => {
          console.log(response);
          if (response.state === true){
            this.page.list[index].password = response.data.resetPassword
            this.$message.success({ message: response.message });
          }else {
            this.$message.warning({ message: response.message });
          }
        })
      },
      toCart(userId){
        this.$router.push(`/cart/${userId}`)
      },
      toUserOrder(userId){
        this.$router.push(`/order/userOrder/${userId}`)
      },
      open(){
        this.$confirm(`此操作将验证, 是否继续？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
      },
      submitForm(formName) {//
        if (formName === "modifyAllInfoForm" && this.loading) {
          //如果是修改信息表单要先查询，等待loading状态结束
          console.log("还在加载中")
          return;
        }
        console.log(this.globalIndex)
        console.log(this.modifyAllInfoForm)

        this.$refs[formName].validate((valid) => {
          if (valid) {
            //this.modifyAllInfoForm.state = this.modifyAllInfoForm.state ^ 1
            modifyUserInfoReq(this.modifyAllInfoForm).then(response =>{
              if (response.state === true) {
                this.$set(this.page.list, this.globalIndex, this.modifyAllInfoForm)
                this.modifyAllInfoDialog = false;//关闭dialog
                this.$notify.success({title: '成功',message: response.message, duration: 1500});
              }else{
                this.$notify.warning({title: '失败',message: response.message, duration: 1500});
              }
            })
          } else {
            this.$notify.error({title: '错误', message: '验证不通过'});
          }
        });
      },
      getInfo(index, user_id){
        console.log(index, user_id)
        this.globalIndex = index;
        this.modifyAllInfoDialog = true;//打开修改信息的弹窗
        this.dialogLoading = true;//进入加载

        getUserByIdReq({userId: user_id}).then(response =>{
          console.log(response)
          if (response.state === true) {
            this.modifyAllInfoForm = response.data.user;//显示信息
            this.dialogLoading = false;//取消加载
            this.$notify.success({title: '成功',message: response.message, duration: 1500});
          }else{
            this.$notify.warning({title: '失败',message: response.message, duration: 1500});
          }
        })
      },
      modifyState(index, userId, state){
        console.log(state)
        state = state ^ 1
        console.log(state)
        modifyStateReq({userId: userId, state: state}).then(response =>{
          if (response.state === true) {
            this.page.list[index].state = state
            this.$notify.success({title: '成功',message: response.message, duration: 1500});
          }else{
            this.$notify.warning({title: '失败',message: response.message, duration: 1500});
          }
        })
      },
      init(){//初始化数据
        this.listLoading = true
        getUserListReq({ condition : this.condition }).then(response => {
          console.log(response)
          if (response.state === true) {
            this.page = response.data.page
            this.$notify.success({title: '成功',message: response.message, duration: 1500});
          }else{
            this.$notify.warning({title: '失败',message: response.message, duration: 1500});
          }
        }).finally(_=>{this.listLoading = false})
      },
      viewAll(){//查看全部用户
        Object.assign(this.$data.condition, this.$options.data().condition);
        this.init();
      },
      handleCurrentChange(currentPage){//处理分页数据
        this.condition.currentPage = currentPage;
        this.init()
      },
      handleState(){
        console.log(this.condition)
      },
      handleClose(done) {
        this.$confirm('确认关闭？').then(_ => {done();}).catch(_ => {});
      },
    },
    filters: {
      genderFilter(genderCode){
        switch (genderCode) {
          case 0 : return "未知";
          case 1 : return "男";
          case 2 : return "女";
        }
      },
      // 时间戳转换成时间
      timestampToTime (timestamp) {
        let date = new Date(timestamp) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        let Y = date.getFullYear() + '-'
        let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
        let D = date.getDate() + ' '
        let h = date.getHours() + ':'
        let m = date.getMinutes() + ':'
        let s = date.getSeconds()
        s = s < 10 ? '0' + s : s;
        return Y+M+D+h+m+s;
      },
    },
    beforeMount (){//初始化数据
      this.init();
    },
    mounted(){
    },
  }
</script>

<style scoped>
>>>.el-table__body-wrapper::-webkit-scrollbar {
  width: 8px; /*滚动条宽度*/
  height: 8px; /*滚动条高度*/
}
>>>.el-table__body-wrapper::-webkit-scrollbar-track {
  border-radius: 10px; /*滚动条的背景区域的圆角*/
  -webkit-box-shadow: inset 0 0 6px rgba(238,238,238, 0.3);
  background-color: #eeeeee; /*滚动条的背景颜色*/
}
>>>.el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 10px; /*滚动条的圆角*/
  -webkit-box-shadow: inset 0 0 6px rgba(145, 143, 0143, 0.3);
  background-color: rgb(145, 143, 143); /*滚动条的背景颜色*/
}


  @media (max-width: 1100px){
    .media-display{
      display: none;
    }
  }
  .el-form{
    width: auto;
  }
  *{
    outline: none;
  }

  .el-card__header{
    background-color: rgba(0,0,0,.03);
  }
  .el-card__body{
    padding-top: 0;
  }
  .clearfix{
    display: flex;
    align-items: center;
  }
  .text {
    font-size: 14px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  tr{
    height: 60px;
  }
  .demo-table-expand {
    font-size: 0;
  }
  >>> .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .el-form--inline .el-form-item__content{
    vertical-align: baseline;
  }
  .el-switch__label{
    color: #909399;
  }

  /*重写switch的disabled时css*/
  >>>.el-switch.is-disabled{
    opacity: 1;
  }
  >>>.el-switch.is-disabled .el-switch__core, .el-switch.is-disabled .el-switch__label{
    cursor: pointer;
  }

  .switch-disabled{
    cursor: no-drop;
  }

  /*头部搜索*/
  .box-card .el-form-item{
    margin-bottom: 0;
  }
  .el-switch{
    vertical-align: baseline;
  }
</style>
